// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
import androidx.compose.animation.core.*
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowState
import androidx.compose.ui.window.application
import cn.hutool.core.util.CharsetUtil
import cn.hutool.core.util.HexUtil
import com.fazecast.jSerialComm.SerialPort
import com.fazecast.jSerialComm.SerialPortDataListener
import com.fazecast.jSerialComm.SerialPortEvent


@Composable
@Preview
fun App() {

    // 定义初始动画
    val infiniteTransaction = rememberInfiniteTransition()

    var switch by remember { mutableStateOf(false) }

    var switchText by remember { mutableStateOf("开启风扇") }

    // 最大温度
    var maxTemperature by remember { mutableStateOf("40") }
    var minTemperature by remember { mutableStateOf("20") }

    var sliderValue by remember { mutableStateOf(0f) }

    var temperature by remember { mutableStateOf("25") }
    var humidity by remember { mutableStateOf("60") }

    // 秒针角度定义
    // 设置初始值
    val normalAngle by infiniteTransaction.animateFloat(
        initialValue = 0f,
        targetValue = if (switch) 360f else 0f,
        animationSpec = infiniteRepeatable(
            animation = tween(300, easing = LinearEasing)
        )
    )

    Column(
        modifier = Modifier.width(300.dp)
            .fillMaxHeight()
            .paint(
                painter = painterResource("dlam.jpg"),
                alpha = 0.2f,
                contentScale = ContentScale.Inside
            )
            .background(Color(20, 133, 143, 150)),
        verticalArrangement = Arrangement.SpaceEvenly,
    ) {
        Row(modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
            ) {
            Text(text = "智能温控风扇系统",
                style = MaterialTheme.typography.h5,
                color = Color.White
            )
        }

        Row(modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Canvas(modifier = Modifier.size(200.dp, 200.dp),
                onDraw = {
                    // Head
                    drawCircle(
                        Brush.linearGradient(
                            colors = listOf(Color.Red, Color.Green)
                        ),
                        radius = size.width / 2,
                        center = center,
                        style = Stroke(width = 5.0f)
                    )

                    // 画一个中心圆点
                    drawCircle(
                        color = Color.Black,
                        radius = 4.0f,
                        center = center
                    )

                    rotate(degrees = normalAngle) {

                        // 弧度值
                        val rad = Math.PI * 2 / 360 * 20 * 6
                        val length = (size.width / 2 - size.width * 0.075f * 0.5)

                        // 画秒针
                        drawLine(
                            color = Color.Black,
                            start = center,
                            end = center + Offset((Math.sin(rad) * length).toFloat(), (-Math.cos(rad) * length).toFloat()),
                            strokeWidth = 2.0f
                        )
                    }

                    rotate(degrees = normalAngle) {

                        // 弧度值
                        val rad = Math.PI * 2 / 360 * 40 * 6
                        val length = (size.width / 2 - size.width * 0.075f * 0.5)

                        // 画秒针
                        drawLine(
                            color = Color.Black,
                            start = center,
                            end = center + Offset((Math.sin(rad) * length).toFloat(), (-Math.cos(rad) * length).toFloat()),
                            strokeWidth = 2.0f
                        )
                    }

                    rotate(degrees = normalAngle) {

                        // 弧度值
                        val rad = Math.PI * 2 / 360 * 60 * 6
                        val length = (size.width / 2 - size.width * 0.075f * 0.5)

                        // 画秒针
                        drawLine(
                            color = Color.Black,
                            start = center,
                            end = center + Offset((Math.sin(rad) * length).toFloat(), (-Math.cos(rad) * length).toFloat()),
                            strokeWidth = 2.0f
                        )
                    }

                }
            )
        }

        Divider(modifier = Modifier.height(2.dp))

        Row(
            modifier = Modifier.height(20.dp).padding(0.dp),
            verticalAlignment = Alignment.Top,
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {

            Text(text = "温度：${temperature}°C, 湿度 ${humidity}%", color = Color.White)

            // 启动一个定时任务
            val comPort = SerialPort.getCommPort("COM3") // 替换为你要使用的串口号

            comPort.baudRate = 9600
            comPort.numDataBits = 8
            comPort.numStopBits = SerialPort.ONE_STOP_BIT
            comPort.parity = SerialPort.NO_PARITY

            try {
                comPort.openPort()

                // 睡眠3S
                Thread.sleep(3000)

                val buffer = ByteArray(1024)
                // 读取串口数据到buffer
                val length = comPort.inputStream.read(buffer)
                if (length > 0) {
                    val data = HexUtil.encodeHexStr(buffer)
                    println("receive resp from device, ${data}")

                    // 解析数据，获取温度和湿度
                    // 假设数据格式为 "T:25.0,H:50.0"
                    val temperatureStr = data.substring(data.indexOf("T:") + 2, data.indexOf(","))
                    val humidityStr = data.substring(data.indexOf("H:") + 2, data.indexOf("."))

                    temperature = temperatureStr
                    humidity = humidityStr
                }

                /*comPort.addDataListener(
                    object : SerialPortDataListener {
                        override fun getListeningEvents(): Int {
                            return SerialPort.LISTENING_EVENT_DATA_AVAILABLE
                        }

                        override fun serialEvent(event: SerialPortEvent) {
                            if (event.getEventType() == SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
                                val inputStream = comPort.inputStream
                                val buffer = ByteArray(1024)
                                val length = inputStream.read(buffer)
                                val data = HexUtil.encodeHexStr(buffer)

                                println("receive resp from device, ${data}")

                                // 解析数据，获取温度和湿度
                                // 假设数据格式为 "T:25.0,H:50.0"
                                val localTemperature = data.substring(data.indexOf("T:") + 2, data.indexOf("H:"))
                                val localHumidity = data.substring(data.indexOf("H:") + 2, data.indexOf(";"))

                                // 打印温度和湿度
                                println("Temperature: $localTemperature°C")
                                println("Humidity: $localHumidity%")

                                // 设置温度和湿度
                                temperature = localTemperature
                                humidity = localHumidity
                            }
                        }
                    }
                )*/
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }

        }

        Divider(modifier = Modifier.height(2.dp))

        Row(
            modifier = Modifier.height(20.dp).padding(0.dp),
            verticalAlignment = Alignment.Top,
            horizontalArrangement = Arrangement.Start
        ) {
            Switch(switch, onCheckedChange = {
                switch = it
                if(switch) {
                    switchText = "关闭风扇"
                } else {
                    switchText = "开启风扇"
                }
            })
            Text(text = switchText)

        }

        Row(modifier = Modifier.fillMaxWidth().padding(0.dp),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            // 输入限制
            // 温度超过最大值时，打开风扇，温度低于最小值时关闭风扇
            OutlinedTextField(
                modifier = Modifier.width(100.dp).padding(0.dp).height(60.dp),
                value = maxTemperature,
                label = { Text(text = "温度上限") },
                onValueChange = {
                    maxTemperature = it
                })

            Spacer(modifier = Modifier.width(10.dp))

            OutlinedTextField(
                modifier = Modifier.width(100.dp).padding(0.dp).height(60.dp),
                value = minTemperature,
                label = { Text(text = "温度下限") },
                onValueChange = {
                    minTemperature = it
                })
        }

        Divider(modifier = Modifier.height(2.dp))

        Row(modifier = Modifier.fillMaxWidth().padding(0.dp),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            // 使用 Slider 组件
            Slider(
                modifier = Modifier.width(200.dp),
                value = sliderValue,
                onValueChange = { sliderValue = it },
                // 可选参数，设置滑动条的最小值和最大值
                valueRange = 0f..100f,
                onValueChangeFinished = {
                    // 停止滑动时，根据滑动条的值判断是否打开风扇
                    if(sliderValue > maxTemperature.toInt()) {
                        switch = true
                        switchText = "关闭风扇"
                    } else if(sliderValue < minTemperature.toInt()){
                        switch = false
                        switchText = "开启风扇"
                    }
                }
            )

            // 当前值的文本显示
            Text(
                text = "${sliderValue.toInt()}°C", // 显示当前值，转换为整数并加上百分号
                fontSize = 16.sp, // 设置字体大小
                color = MaterialTheme.colors.onSurface, // 设置文本颜色
                modifier = Modifier
                    .align(Alignment.CenterVertically) // 文本对齐方式
            )
        }



    }

}

fun main() = application {
    Window(onCloseRequest = ::exitApplication,
        state = WindowState(width = 300.dp, height = 600.dp),
        resizable = false,
        title = "时钟",
        icon = painterResource("time.png"),
        undecorated = true
    ) {
        WindowDraggableArea {
            App()
        }
    }
}

fun getTemperatureAndHumidity() {


}

